package com.core.common;


import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.map.annotate.JsonSerialize;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
//保证序列化json的时候,如果是null的对象,key也会消失
public class ServerResponse<T> implements Serializable {
    private static final int SYSTEM_ERROR = 512;

    private int status;
    private String msg;
    private T data;

    private ServerResponse(int status){
        this.status = status;
    }

    private ServerResponse(int status, T data){
        this.status = status;
        this.data = data;
    }

    private ServerResponse(int status, String msg, T data){
        this.status = status;
        this.msg = msg;
        this.data = data;
    }

    private ServerResponse(int status, String msg){
        this.status = status;
        this.msg = msg;
    }

    @JsonIgnore(value = false)
    //使之不在json序列化结果当中
    public boolean isSuccess(){
        return this.status == ResponseCode.OK.getCode();
    }

    public Map<String , Object> toMap(){
        Map<String,Object> res = new HashMap<String,Object>();
        res.put("status",status);
        res.put("msg",msg);
        res.put("data",data);
        return res;
    }

    public static <T> ServerResponse<T> success(){
        return new ServerResponse<T>(ResponseCode.OK.getCode());
    }

    public static <T> ServerResponse<T> success(int messageCode,String msg){
        return new ServerResponse<T>(ResponseCode.OK.getCode(),msg);
    }

    public static <T> ServerResponse<T> success(T data){
        return new ServerResponse<T>(ResponseCode.OK.getCode(),data);
    }

    public static <T> ServerResponse<T> success(String msg,T data){
        return new ServerResponse<T>(ResponseCode.OK.getCode(),msg,data);
    }

    /**指定异常*/
    public static <T> ServerResponse<T> fail(int messageCode,String messageDesc){
        return new ServerResponse<T>(messageCode,messageDesc);
    }
    /**指定异常*/
    public static <T> ServerResponse<T> fail(ResponseCode code){
        return new ServerResponse<T>(code.getCode(),code.getDescCN());
    }
    /**系统异常*/
    public static <T> ServerResponse<T> fail(Exception ex){
        return fail(SYSTEM_ERROR,ex.getMessage());
    }
}


